import sqlite3
import random
from hashlib import md5
def create_recipe(db, file_path):
    con = sqlite3.connect(db)
    #you can select a bunch of blocks like this
    res = con.execute('select * from blocks limit 100'); 
    bids = []     #block ids
    bdatas = [] #block data
    for row in res:
        bids.append(row[0])
        bdatas.append(str(row[1]))
    #your algorithm here that generates xids & yids s.t. 
    #the file is the concatenation of xids[i]^yids[i]
    xids = [] #ids corresponding to blocks in the database
    yids = [] #ids corresponding to new blocks needed to rebuild file
    pad_bytes = 0 #number of pad bytes needed, default to 0

    f = open(file_path, "rb")
    tempFile = f.read()
    filesize = len(tempFile)
    
    for block in bdatas:
        if (len(tempFile) == 0):
            break
        if (len(tempFile) < len(block)):
            pad_bytes = len(block) - len(tempFile)
            for i in range(pad_bytes):
                #pad file up to multiple of block length
                tempFile.append(chr(random.randrange(0, 256)))
        
        ba_block = bytearray(block)
        ba_file = bytearray(tempFile[0:len(block)])
        xorBlock = []
        for i in range(0, len(block)):
            xorBlock.append(ba_block[i] ^ ba_file[i])

        add xorBlock to DB?
        tempFile = tempFile[len(block):]
        xids.append(md5(block))
        yids.append(md5(xorBlock))

    recipe = Recipe(filename, filesize, xids, yids, pad_bytes)
    return recipe


    # for each block in bdatas
    #   if (len(tempFile) == 0):
    #       break
    #   if (len(tempFile) < len(block)):
    #       block = block[0:len]
    #       add fillerBlock to DB
    #       newBlock = fillerBlock XOR file block
    #       add newBlock to database
    #   newBlock = block XOR file block
    #   add newBlock to database
    #   add id of block to xids, newBlock to yids
    # return recipe
    
